<?php
class Database
{
    /**
     * PDO to use
     *
     * @var PDO
     */
    protected $_pdo;

    public function __construct($host,$dbname,$username,$password)
    {
        $dsn = "mysql:host=$host";
        if($dbname != '')
        	$dsn = $dsn.";dbname=$dbname";

        try
        {
            $this->_pdo = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
        }
        catch (PDOException $e)
        {
            $this->_pdo = null;
        }
    }
    
    public function getPDO()
    {
    	return $this->_pdo;
    }
    
    public function execSQL($statement)
    {
    	return $this->_pdo->exec($statement);
    }
    
    public function createDatabase($dbname)
    {
    	$this->execSQL("DROP DATABASE IF EXISTS $dbname");
    	$this->execSQL("CREATE DATABASE  $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
    }
    
	/**
	 *
	 * Chia mot chuoi lenh sql thanh tung lenh
	 * @param string $sql
	 * @return array $queries
	 * 
	 */
	public function splitQueries($sql)
	{
		// Initialise variables.
		$buffer		= array();
		$queries	= array();
		$in_string	= false;

		// Trim any whitespace.
		$sql = trim($sql);

		// Remove comment lines.
		//$sql = preg_replace("/\n\#[^\n]*/", '', "\n".$sql);
		$sql = preg_replace("/\n\--[^\n]*/", '', "\n".$sql);
		// Parse the schema file to break up queries.
		for ($i = 0; $i < strlen($sql) - 1; $i ++)
		{
			if ($sql[$i] == ";" && !$in_string) {
				$queries[] = substr($sql, 0, $i);
				$sql = substr($sql, $i +1);
				$i = 0;
			}

			if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
				$in_string = false;
			}
			elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset ($buffer[0]) || $buffer[0] != "\\")) {
				$in_string = $sql[$i];
			}
			if (isset ($buffer[1])) {
				$buffer[0] = $buffer[1];
			}
			$buffer[1] = $sql[$i];
		}

		// If the is anything left over, add it to the queries.
		$sql = trim($sql);
		if (!empty($sql)) {
			$queries[] = $sql;
		}

		return $queries;
	}
	
	public function importSql($sql)
	{
		$queries = $this->splitQueries($sql);
		if($queries != null)
		{
			$countQueries = count($queries);
			for ($i = 0; $i < $countQueries; $i++) 
			{
				$this->execSQL($queries[$i]);
			}
		}
	}
}